'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { FileSpreadsheet, LineChart as LineChartIcon, TrendingUp } from 'lucide-react';
import { formatMoney, getApiUrl } from '@/lib/utils';
import {
  LineChart,
  Line,
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from 'recharts';

const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042'];

interface MonthlyExpense {
  month: string;
  total: number;
  material: number;
  labor: number;
  equipment: number;
  other: number;
  accumulated: number;
}

function ExpenseTrendAnalysis({ data }: { data: MonthlyExpense[] }) {
  // 计算月平均支出
  const monthlyAverage = data.reduce((acc, month) => acc + month.total, 0) / data.length;

  // 计算环比增长
  const lastMonthExpense = data[data.length - 1].total;
  const previousMonthExpense = data[data.length - 2].total;
  const monthOverMonthGrowth = previousMonthExpense === 0 
    ? 0 
    : ((lastMonthExpense - previousMonthExpense) / previousMonthExpense) * 100;

  return (
    <div className="space-y-6">
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">本月支出</CardTitle>
            <TrendingUp className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{formatMoney(lastMonthExpense)}</div>
            <p className="text-xs text-muted-foreground">
              环比
              <span className={monthOverMonthGrowth > 0 ? 'text-red-500' : 'text-green-500'}>
                {monthOverMonthGrowth > 0 ? '↑' : '↓'} {Math.abs(monthOverMonthGrowth).toFixed(1)}%
              </span>
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">月平均支出</CardTitle>
            <TrendingUp className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{formatMoney(monthlyAverage)}</div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">累计支出</CardTitle>
            <TrendingUp className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {formatMoney(data[data.length - 1].accumulated)}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">统计月份</CardTitle>
            <TrendingUp className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{data.length}个月</div>
          </CardContent>
        </Card>
      </div>

      <div className="grid gap-4 md:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle>月度支出趋势</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="h-[400px]">
              <ResponsiveContainer width="100%" height="100%">
                <AreaChart
                  data={data}
                  margin={{
                    top: 10,
                    right: 30,
                    left: 0,
                    bottom: 0,
                  }}
                >
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="month" />
                  <YAxis />
                  <Tooltip formatter={(value: number) => formatMoney(value)} />
                  <Legend />
                  <Area
                    type="monotone"
                    dataKey="material"
                    name="材料费"
                    stackId="1"
                    stroke={COLORS[0]}
                    fill={COLORS[0]}
                  />
                  <Area
                    type="monotone"
                    dataKey="labor"
                    name="人工费"
                    stackId="1"
                    stroke={COLORS[1]}
                    fill={COLORS[1]}
                  />
                  <Area
                    type="monotone"
                    dataKey="equipment"
                    name="设备费"
                    stackId="1"
                    stroke={COLORS[2]}
                    fill={COLORS[2]}
                  />
                  <Area
                    type="monotone"
                    dataKey="other"
                    name="其他费用"
                    stackId="1"
                    stroke={COLORS[3]}
                    fill={COLORS[3]}
                  />
                </AreaChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>累计支出趋势</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="h-[400px]">
              <ResponsiveContainer width="100%" height="100%">
                <LineChart
                  data={data}
                  margin={{
                    top: 10,
                    right: 30,
                    left: 0,
                    bottom: 0,
                  }}
                >
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="month" />
                  <YAxis />
                  <Tooltip formatter={(value: number) => formatMoney(value)} />
                  <Legend />
                  <Line
                    type="monotone"
                    dataKey="accumulated"
                    name="累计支出"
                    stroke="#8884d8"
                    strokeWidth={2}
                  />
                </LineChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

export default function ExpenseTrendReportPage() {
  const [data, setData] = useState<MonthlyExpense[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    async function loadData() {
      try {
        const response = await fetch(getApiUrl('reports/by-time'));
        if (!response.ok) throw new Error('加载数据失败');
        const data = await response.json();
        setData(data);
      } catch (error) {
        console.error('加载数据失败:', error);
      } finally {
        setIsLoading(false);
      }
    }
    loadData();
  }, []);

  return (
    <main className="container mx-auto p-4 space-y-4">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">支出趋势分析</h1>
          <p className="text-muted-foreground">
            查看支出的月度变化趋势和累计情况
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" asChild>
            <Link href="/reports">
              <LineChartIcon className="mr-2 h-4 w-4" />
              总览报表
            </Link>
          </Button>
          <Button>
            <FileSpreadsheet className="mr-2 h-4 w-4" />
            导出报表
          </Button>
        </div>
      </div>

      {isLoading ? (
        <div>加载中...</div>
      ) : (
        <ExpenseTrendAnalysis data={data} />
      )}
    </main>
  );
} 